package com.lgmshare.component.storage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 使用SQLiteOpenHelper对数据库进行版本管理
 *
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2017/11/22 17:17
 */
class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "wk.db";
    private static final String DATABASE_TABLE_NAME = "t_dictionary";

    private static DatabaseHelper INSTANCE;

    /**
     * 使用懒加载
     *
     * @param context
     * @return
     */
    public static DatabaseHelper getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new DatabaseHelper(context);
        }
        return INSTANCE;
    }

    public DatabaseHelper(Context context) {
        this(context, DATABASE_NAME, null, 1);
    }

    public DatabaseHelper(Context context, String name, int version) {
        this(context, name, null, version);
    }

    public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        this(context, name, factory, version, null);
    }

    public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //m-所属模块  k-key  v-value,d-时间日期
        db.execSQL("create table if not exists " + DATABASE_TABLE_NAME + "("
                + "id integer primary key,"
                + "k varchar(16),"
                + "v varchar(100),"
                + "d long)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //db.execSQL("");
    }

    /**
     * 清空表数据
     */
    public void clear() {
        getWritableDatabase().execSQL("delete from " + DATABASE_TABLE_NAME);
    }

    /**
     * 添加数据
     *
     * @param key
     * @param value
     * @return the row ID of the newly inserted row, or -1 if an error occurred
     */
    public long insert(String key, String value) {
        if (null == query(key)) {
            ContentValues values = new ContentValues(3);
            values.put("k", key);
            values.put("v", value);
            values.put("d", System.currentTimeMillis());
            return getWritableDatabase().insert(DATABASE_TABLE_NAME, null, values);
        } else {
            return update(key, value);
        }
    }

    /**
     * 删除数据
     *
     * @param key
     * @return the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
     */
    public int delete(String key) {
        //删除条件（where字句）
        String whereClause = "k=?";
        //删除条件值数组
        String[] whereArgs = new String[]{key};
        //更行列ContentValues类型的键值对（Map）
        return getWritableDatabase().delete(DATABASE_TABLE_NAME, whereClause, whereArgs);
    }

    /**
     * 查询数据
     *
     * @param key
     * @return
     */
    public String query(String key) {
        String selection = "k=?";
        String[] selectionArgs = new String[]{key};
        String[] columns = new String[]{"v"};
        String value = null;
        Cursor cursor = getReadableDatabase().query(DATABASE_TABLE_NAME, columns, selection, selectionArgs, null,
                null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            int rowCount = cursor.getCount();
            for (int i = 0; i < rowCount; i++) {
                value = cursor.getString(cursor.getColumnIndex("v"));
                cursor.moveToNext();
                break;
            }
        }
        if (cursor != null) {
            cursor.close();
        }
        return value;
    }

    /**
     * 更新数据
     *
     * @param key
     * @param value
     * @return
     */
    public int update(String key, String value) {
        //更新条件（where字句）
        String whereClause = " k=?";
        //更新条件数组
        String[] whereArgs = new String[]{key};
        //更行列ContentValues类型的键值对（Map）
        ContentValues values = new ContentValues(2);
        values.put("v", value);
        values.put("d", System.currentTimeMillis());
        return getWritableDatabase().update(DATABASE_TABLE_NAME, values, whereClause, whereArgs);
    }

}
